package wps.component.elementsetting {

import mx.binding.utils.BindingUtils;
import mx.controls.DataGrid;
import mx.events.FlexEvent;

import wps.util.EnableChecker;

public class SettingDataGrid extends DataGrid implements ISettingItem {

    //--------------------------------------------------------------------------
    //
    // Properties
    //
    //--------------------------------------------------------------------------

    private var _target:Object;

    private var _targetProperty:String;

    private var _needCopy:Boolean = false;

    //--------------------------------------------------------------------------
    //
    // Constructor
    //
    //--------------------------------------------------------------------------

    public function SettingDataGrid() {
        super();

        addEventListener(FlexEvent.INITIALIZE, initializeHandler);
    }

    //--------------------------------------------------------------------------
    //
    // Methods
    //
    //--------------------------------------------------------------------------

    public function get needCopy():Boolean {
        return _needCopy;
    }

    public function set needCopy(needCopy:Boolean):void {
        _needCopy = needCopy;
    }

    [Bindable]
    public function get target():Object {
        return _target;
    }

    public function set target(target:Object):void {
        _target = target;
        targetChanged();
    }

    public function get targetProperty():String {
        return _targetProperty;
    }

    public function set targetProperty(targetProperty:String):void {
        _targetProperty = targetProperty;
        targetPropertyChanged();
    }

    public function get targetStyle():String {
        return null;
    }

    public function set targetStyle(targetStyle:String):void {

    }

    public function checkEnable():void {
        var checker:EnableChecker = new EnableChecker(this);
        enabled = checker.getEnableValue();
    }

    private function targetChanged():void {
        checkEnable();
        targetPropertyChanged();
    }

    private function targetPropertyChanged():void {
        if (targetProperty) {
            BindingUtils.bindSetter(propertySetter, target, targetProperty);
        }
    }

    protected function propertySetter(value:Object):void {
        if (target && targetProperty) {
            this[targetProperty] = target[targetProperty];
        }
    }

    //--------------------------------------------------------------------------
    //
    // Event handlers
    //
    //--------------------------------------------------------------------------

    private function initializeHandler(e:FlexEvent):void {
        enabled = target ? true : false;
    }

}

}
